package com.EmployeeButler.controller;


import cn.dev33.satoken.stp.StpUtil;
import cn.dev33.satoken.util.SaResult;
import com.EmployeeButler.entity.Attendance;
import com.EmployeeButler.entity.Salary;
import com.EmployeeButler.entity.vo.AttendanceVo;
import com.EmployeeButler.entity.vo.CountVo;
import com.EmployeeButler.mapper.AttendanceMapper;
import com.EmployeeButler.service.IAttendanceService;
import com.EmployeeButler.utils.MyTool;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.apache.tomcat.util.http.SameSiteCookies;
import org.assertj.core.error.ShouldNotEndWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author 作者
 * @since 2024-06-13
 */
@Controller
@RequestMapping("/attendance")
public class AttendanceController {

    @Autowired
    private IAttendanceService attendanceService;

    @Autowired
    AttendanceMapper attendanceMapper;

    @GetMapping("/show")
    public String show(Model model) {
        List<AttendanceVo> attendanceVos = attendanceService.getAttendanceShow();
        model.addAttribute("attendanceVos", attendanceVos);
        List<CountVo> countVos = attendanceMapper.getPushCount();
        model.addAttribute("countVos", countVos);
        return "admin/attendances";
    }

    @GetMapping("/list")
    public String search(@RequestParam(required = false) String keyword, Model model) {
        // 定义用户列表
        List<Attendance> attendances;

        // 检查关键字是否为空
        if (keyword == null || keyword.isEmpty()) {
            attendances = attendanceService.list();
        } else {
            attendances = attendanceService.list(new QueryWrapper<Attendance>()
                    .like("user_id", keyword));
        }
        // 将用户列表添加到模型中
        model.addAttribute("attendances", attendances);
        return "/admin/records";
    }

    @GetMapping
    public String getAttendance() {
        return "user/attendance";
    }

    @GetMapping("/me")
    public String getAttendanceOfMe(Model model) {
        List<Attendance> attendances = attendanceService.list(new QueryWrapper<Attendance>()
                .eq("user_id", MyTool.getLoginId()));
        model.addAttribute("attendances", attendances);
        model.addAttribute("count", attendances.size());
        return "user/me";
    }

    @PostMapping
    @ResponseBody
    public SaResult addAttendance(Attendance attendance) {
        attendance.setCheckTime(LocalDateTime.now());
        attendance.setUserId(MyTool.getLoginId());
        attendanceService.save(attendance);
        return SaResult.ok();
    }

}
